package com.chen.leet_code.answer;

/**
 * Definition for singly-linked list.
 *
 */
class Solution19 {
    public ListNode removeNthFromEnd(ListNode head, int n) {

        ListNode first = head;
        ListNode second = head;
        int pos =0;
        //首先将first 向后移动N个
        while (first.next !=null){
            first = first.next;
            if(++pos>=n){
                break;
            }
        }
        if(pos<n){ //这里防止出现 只有两个元素，然后移除倒数第二个这种情况
            return head.next;
        }
        while (first.next !=null){
            first = first.next;
            second = second.next;
        }
        if(second.next ==null){
            return null;
        }


        ListNode middle = second.next;
        second.next = middle.next;
        middle.next=null;
        return  head;

    }

    public class ListNode {
       int val;
       ListNode next;
       ListNode() {}
      ListNode(int val) { this.val = val; }
       ListNode(int val, ListNode next) { this.val = val; this.next = next; }
   }
}